# 使用锁的机制来实现线程同步
from threading import Thread, Lock
import time
import os
from random import randint

# 定义一个锁
threadlock = Lock()


class MyThreadClass(Thread):
    def __init__(self, name, duration):
        Thread.__init__(self)  # 创建一个线程类
        self.name = name
        self.duration = duration

    # 对线程类调用start时就会运行线程类的run函数
    def run(self):
        # 获得锁
        threadlock.acquire()
        print("---> " + self.name + " running, belonging to process ID " + str(os.getpid()) + "\n")
        time.sleep(self.duration)
        print("---> " + self.name + " over\n")
        threadlock.release()  # 释放锁，这样的9个线程会顺序执行，当第一个锁释放以后，第二个线程才会获得锁，第二个线程才会开始执行


def main():
    start_time = time.time()
    thread1 = MyThreadClass('Thread#1', randint(1, 10))
    thread2 = MyThreadClass('Thread#2', randint(1, 10))
    thread3 = MyThreadClass('Thread#3', randint(1, 10))
    thread4 = MyThreadClass('Thread#4', randint(1, 10))
    thread5 = MyThreadClass('Thread#5', randint(1, 10))
    thread6 = MyThreadClass('Thread#6', randint(1, 10))
    thread7 = MyThreadClass('Thread#7', randint(1, 10))
    thread8 = MyThreadClass('Thread#8', randint(1, 10))
    thread9 = MyThreadClass('Thread#9', randint(1, 10))

    thread1.start()
    thread2.start()
    thread3.start()
    thread4.start()
    thread5.start()
    thread6.start()
    thread7.start()
    thread8.start()
    thread9.start()

    thread1.join()
    thread2.join()
    thread3.join()
    thread4.join()
    thread5.join()
    thread6.join()
    thread7.join()
    thread8.join()
    thread9.join()
    end_time = time.time()
    print('End!')

    print('---%s seconds---' % (end_time - start_time))


if __name__ == '__main__':
    main()
